import { createStore } from 'vuex'
import router from '@/router'

const setItem = (key, value) => {
  // 将数组、对象类型的数据转化为 JSON 字符串进行存储
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  window.localStorage.setItem(key, value)
}

export default createStore({
  state: {
    userName: {},
    sidebarOpened: true,
    tagsViewList: []
  },
  getters: {
    userName: (state) => state.userName,
    sidebarOpened: (state) => state.sidebarOpened,
    tagsViewList: (state) => state.tagsViewList
  },
  mutations: {
    setUserName(state, userName) {
      state.userName = userName
    },
    triggerSidebarOpened(state) {
      state.sidebarOpened = !state.sidebarOpened
    },
    initTagsViewList(state) {
      state.tagsViewList = []
    },
    /**
     * 添加 tags
     */
    addTagsViewList(state, tag) {
      const isFind = state.tagsViewList.find((item) => {
        return item.path === tag.path
      })
      // 处理重复
      if (!isFind) {
        state.tagsViewList.push(tag)
        setItem('tagsView', state.tagsViewList)
      }
    },
    /**
     * 为指定的 tag 修改 title
     */
    changeTagsView(state, { index, tag }) {
      state.tagsViewList[index] = tag
      setItem('tagsView', state.tagsViewList)
    },
    removeTagsView(state, payload) {
      if (payload.type === 'index') {
        state.tagsViewList.splice(payload.index, 1)
        return
      } else if (payload.type === 'other') {
        state.tagsViewList.splice(
          payload.index + 1,
          state.tagsViewList.length - payload.index + 1
        )
        state.tagsViewList.splice(0, payload.index)
      } else if (payload.type === 'right') {
        state.tagsViewList.splice(
          payload.index + 1,
          state.tagsViewList.length - payload.index + 1
        )
      }
      setItem('tagsView', state.tagsViewList)
    }
  },
  actions: {
    logout() {
      this.commit('setUserName', {})
      this.commit('initTagsViewList')
      router.push('/login')
    }
  },
  modules: {}
})
